<template>
    <div class="ct-bodySet">
        <el-container class="backgroubd_div">
            <el-header class="bgclr-dk-sp0 mb20 headerCoster">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }"
                        >首页</el-breadcrumb-item
                    >
                    <el-breadcrumb-item>资产库</el-breadcrumb-item>
                    <el-breadcrumb-item
                        ><span class="main-Clr-ft"
                            >标准库</span
                        ></el-breadcrumb-item
                    >
                </el-breadcrumb>
            </el-header>
            <el-container class="pl20 pr20" style="display: flex">
                <el-card
                    class="mr15 cardMinWidth autoHeight"
                    style="min-width: 115px"
                >
                    <div slot="header">
                        <span>目录列表</span>
                    </div>
                    <el-input
                        size="small"
                        placeholder="输入关键字进行过滤"
                        v-model="filterText"
                        style="padding-bottom: 10px"
                    >
                    </el-input>
                    <div class="mytree">
                        <el-tree
                            :data="groupTreeData"
                            ref="groupTreeData"
                            :props="groupTreeDataProps"
                            default-expand-all
                            :expand-on-click-node="false"
                            :highlight-current="true"
                            node-key="id"
                            @node-click="clickNode"
                            :filter-node-method="filterNode"
                        >
                            <span slot-scope="{ node, data }">
                                <!--                            <span v-if="data.id==''" class="labelstyleTree tx-Elps main-Clr-ft" :title="node.label" >{{ node.label }}</span>-->
                                <span
                                    class="labelstyleTree tx-Elps"
                                    :title="node.label"
                                    >{{ node.label }}</span
                                >
                            </span>
                        </el-tree>
                    </div>
                </el-card>

                <el-card class="autoHeight cardWidth" style="flex: 1">
                    <template>
                        <!--搜索 -->
                        <el-popover placement="right" trigger="hover">
                            <el-input
                                v-model="search"
                                placeholder="输入关键字搜索"
                            />
                            <el-button
                                class="el-icon-search"
                                type="text"
                                size="medium"
                                slot="reference"
                                style="padding-right: 10px"
                            >
                                搜索
                            </el-button>
                        </el-popover>
                        <el-progress
                            :text-inside="true"
                            :stroke-width="18"
                            :percentage="percentage"
                            status="success"
                            v-if="percentageShow"
                        >
                        </el-progress>
                    </template>
                    <el-table
                        class="mytable"
                        :data="
                            tableData.filter(
                                (data) =>
                                    !search ||
                                    data.fileName
                                        .toLowerCase()
                                        .includes(search.toLowerCase())
                            )
                        "
                        stripe
                        :default-sort = "{prop: 'file_update_date', order: 'descending'}" 
                    >
                        <el-table-column prop="fileName" label="文件名">
                            <template slot-scope="scope">
                                <i class="el-icon-document"></i>
                                <span style="margin-left: 5px">{{
                                    scope.row.fileName
                                }}</span>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="file_suffix" label="类型" width="60"/> -->
                        <el-table-column
                            prop="file_size"
                            label="大小"
                            width="120"
                        >
                            <template slot-scope="scope">
                                <span style="margin-left: 5px"
                                    >{{ scope.row.file_size }}{{ "KB" }}</span
                                >
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="file_upload_usr" label="上传人" width="80" /> -->
                        <el-table-column
                            prop="file_update_date"
                            label="更新时间"
                            width="200"
                        >
                            <template slot-scope="scope">
                                <i class="el-icon-time"></i>
                                <span style="margin-left: 10px">{{
                                    scope.row.file_update_date
                                }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="file_path"
                            label="路径"
                            v-if="false"
                        />
                        <el-table-column label="操作" width="100">
                            <template slot-scope="scope">
                                <!-- <div>
                                    <el-row>
                                    <el-col :span="24">
                                        <el-progress type="circle" :percentage="percentage"></el-progress>
                                        <el-card class="box-card">
                                        <el-row style="float: left;margin-top: 10px;margin-bottom: 10px ">
                                            <el-col :span="24"> -->
                                <el-button 
                                            
                                            type="text" size="medium" @click="preview(scope.row)">预览</el-button>
                                            
                                            <el-button type="text" size="medium" @click="downLoad(scope.row)">下载</el-button>
                                <!-- </el-col>
                                        </el-row>
                                        </el-card>
                                    </el-col>
                                    </el-row>
                                </div> -->
                            </template>
                        </el-table-column>
                        <!-- <el-table-column
                            prop="progress"
                            label="进度"
                            >
                            <template slot-scope="scope">
                                <el-progress
                                type="line"
                                :stroke-width="15"
                                :percentage="percentage"
                                ></el-progress>
                            </template>
                         </el-table-column> -->
                        <!--自定义无数据显示 -->
                        <template slot="empty">
                            <img
                                src="static/icon/暂无文件.png"
                                style="margin-top: 80px"
                            />
                            <p style="padding-top: 5px">暂无数据</p>
                        </template>
                    </el-table>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
import axios from "axios";
import urlConfig from "../../../config/url.json";
import Vue from "vue";
import { Message } from "element-ui";
Vue.component(Message.name, Message);
let fileUploadRecord = urlConfig.queryFileUploadRecord;
let postFileDownloadNumberUrl = urlConfig.postFileDownloadNumber;
let asGroup = urlConfig.asGroupQueryAll;
let queryFileList = urlConfig.queryFileList;
let downloadFile = urlConfig.downloadFile;
let fileOnlineNumber = urlConfig.fileOnlineNumber;
let fileOnlineUrl = urlConfig.fileOnlineUrl;
export default {
    data() {
        return {
            compareFlag: true, //新旧值对比标识,true代表相同
            showFlag: false,
            selectFlag: true,
            flage: false, //标记是否添加
            groupTreeData: [],
            groupTreeDataProps: {
                children: "children",
                label: "libraryName",
            },
            comparFormValue: {}, //比较用数据
            patientRole: {}, //新添加角色的父角色
            tableData: [],
            search: "",
            menuName: "标准库",
            filterText: "",
            form: {
                fileName: "",
                current: 1,
                size: 10,
            },
            fileDataList: [],
            dialogVisible: false,
            file: "",
            percentage: 0,
            percentageShow: false,
             fileOnlinePerviewUrl:''
        };
    },
    //通过关键字过滤树节点
    watch: {
        filterText(val) {
            this.$refs.groupTreeData.filter(val);
        },
    },
    methods: {
                //在线预览
        preview(row){
            debugger
            // let Base64 = require('js-base64').Base64
            // var filename = "平台提档升级接口集成规范.docx";
            // var url = "http://localhost:8080/downLoadFile?name="+filename;
            // var previewUrl = url+"&fullfilename="+filename
            // 这里访问的url是 预览服务的url  刚才你启动了  预览服务 所以这里应该写成 8011
            // window.open('http://127.0.0.1:8011/onlinePreview?url='+encodeURIComponent(Base64.encode(previewUrl)));
            //window.open('http:/localhost:8012/onlinePreview?url='+encodeURIComponent(previewUrl));

            //以下为post方法
            let Base64 = require('js-base64').Base64
            var filename = row.fileName;
            var filepath = row.filePath;
            // var filepath = "测试(我要"+'+'+"吃饭";
            // var url = "http://localhost:9000/api/downLoadFile?name="+filename+"&path="+filepath;
            var url = "http://localhost:9399/api/downLoadFile?name="+filename+"&path="+filepath;
            var previewUrl = url+"&fullfilename="+filename+"&method=post"
            // 这里访问的url是 预览服务的url  刚才你启动了  预览服务 所以这里应该写成 8011
                window.open(this.fileOnlinePerviewUrl+encodeURIComponent(Base64.encode(previewUrl)));
            //  window.open('http://127.0.0.1:8011/onlinePreview?url='+encodeURIComponent(Base64.encode(previewUrl)));
            //记录预览次数
            this.fileOnlineNumber(filename);
        },
        //  下载文件
        downLoad(row) {
            debugger;
            var filepath = row.filePath;
            var filename = row.fileName;
            //下载post请求方式
            let that = this;
            that.$http({
                method: "post",
                url: downloadFile,
                baseURL: "/api",
                data: {
                    name: filename,
                    path: filepath,
                },
                responseType: "blob",
                onDownloadProgress: (progressEvent) => {
                    debugger;
                    that.percentageShow = true;
                    let progressBar = Math.round(
                        (progressEvent.loaded / progressEvent.total) * 100
                    );
                    if (progressBar >= 99) {
                        this.percentage = 99;
                        console.log("下载完成，文件正在编译。");
                    } else {
                        this.percentage = progressBar;
                        console.log("正在下载，请稍等。");
                    }
                },
            })
                .then(function (res) {
                    debugger;
                    console.log(res);
                    let link = document.createElement("a");
                    link.href = URL.createObjectURL(res.data);
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    URL.revokeObjectURL(link.href);
                    //编译文件完成后，进度条展示为100%100
                    that.percentage = 100;
                    // that.percentageShow = false;
                    // loading.close();
                    //记录下载次数
                    that.postFileDownloadNumber(filename);
                })
                .catch(function (err) {
                    console.log(err);
                    Message.error("下载失败");
                    loading.close();
                });
        },
        //获取树的数据
        getTreeData() {
            debugger;
            let that = this;
            const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
            });
            that.$http({
                method: "post",
                url: asGroup,
                baseURL: "/api",
                data: {
                    method: "",
                },
            })
                .then(function (response) {
                    if (response.data.code == 1) {
                        var newdata = response.data.data;
                        that.groupTreeData = that.getJsonTree(newdata, "-1");
                        //只保留当前对象
                        const filteredArray = that.groupTreeData.filter(
                            (item) => {
                                return item.libraryName === that.menuName;
                            }
                        );
                        that.groupTreeData = filteredArray;
                        if (that.groupTreeData.length > 0) {
                            that.getFileTable(that.menuName);
                        }
                    } else {
                        Message.error("获取目录失败");
                    }
                    loading.close();
                })
                .catch(function (err) {
                    console.log(err);
                    Message.error("获取目录失败");
                    loading.close();
                });
        },

        getJsonTree(newdata, parentId) {
            let that = this;
            var itemArr = [];
            for (var i = 0; i < newdata.length; i++) {
                var node = newdata[i];
                if (node.PARENT_ID == parentId) {
                    var newNode = {
                        id: node.ID,
                        libraryName: node.LIBRARY_NAME,
                        parentId: node.PARENT_ID,
                        orderid: node.ORDERID,
                        description: node.DESCRIPTION,
                        createBy: node.CREATE_BY,
                        createDate: node.CREATE_DATE,
                        updateBy: node.UPDATE_BY,
                        updateDate: node.UPDATE_DATE,
                        path: node.PATH,
                        children: that.getJsonTree(newdata, node.ID),
                    };
                    itemArr.push(newNode);
                }
            }
            itemArr.sort(that.up);
            return itemArr;
        },
        //记录在线预览次数
        fileOnlineNumber(filename) {
            debugger;
            let that = this;
            var username = JSON.parse(window.localStorage["loginData"])["username"];
            var groupname =  JSON.parse(that.STORAGE.getItem("groupIdList"))[0].groupName;
            var fileName = filename;
            const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
            });
            that.$http({
                method: "post",
                url: fileOnlineNumber,
                baseURL: "/api",
                data: {
                    groupname:groupname,
                    username: username,
                    fileName: fileName,
                    date:that.sysdate(),
                    asset:that.menuName
                },
            })
                .then(function (response) {
                    // if (response.data.code == 1) {
                    //     // that.company = response.data.data;
                    // } else {
                    //     Message.error("更新下载次数失败");
                    // }
                    loading.close();
                })
                .catch(function (err) {
                    console.log(err);
                    // Message.error("更新下载次数失败");
                    loading.close();
                });
        },

        //记录下载次数
        postFileDownloadNumber(filename) {
            debugger;
            let that = this;
            var username = JSON.parse(window.localStorage["loginData"])[
                "username"
            ];
            var groupname = JSON.parse(that.STORAGE.getItem("groupIdList"))[0]
                .groupName;
            var fileName = filename;
            const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
            });
            that.$http({
                method: "post",
                url: postFileDownloadNumberUrl,
                baseURL: "/api",
                data: {
                    groupname: groupname,
                    username: username,
                    fileName: fileName,
                    date: that.sysdate(),
                    asset: that.menuName,
                },
            })
                .then(function (response) {
                    // if (response.data.code == 1) {
                    //     // that.company = response.data.data;
                    // } else {
                    //     Message.error("更新下载次数失败");
                    // }
                    loading.close();
                })
                .catch(function (err) {
                    console.log(err);
                    // Message.error("更新下载次数失败");
                    loading.close();
                });
        },

        up(x, y) {
            return x.orderid - y.orderid;
        },

        //获取Table数据
        getFileTable(path) {
            debugger;
            let that = this;
            that.$http({
                method: "post",
                url: queryFileList,
                baseURL: "/api",
                data: {
                    path: path,
                },
            })
                .then(function (response) {
                    if (response.data.code == 1) {
                        that.tableData = response.data.data;
                    } else {
                        Message.error("获取文件列表失败");
                    }
                })
                .catch(function (err) {
                    console.log(err);
                    Message.error("获取文件列表失败");
                });
        },

        //点击树节点-->获取组信息
        clickNode(data, node) {
            debugger;
            let that = this;
            that.percentage = 0;
            that.percentageShow = false;
            that.getFileTable(data.path);
        },
        //通过关键字过滤树节点
        filterNode(value, data) {
            debugger;
            if (!value) return true;
            return data.libraryName.indexOf(value) !== -1;
        },
        //日期
        sysdate() {
            //年
            var year = new Date().getFullYear();
            //月份是从0月开始获取的，所以要+1;
            var month = new Date().getMonth() + 1;
            //日
            var day = new Date().getDate();
            return year + "-" + month + "-" + day;
        },
        //uuid
        uuid() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";
            var uuid = s.join("");
            return uuid;
        },
        //获取url
        getFileOnlineUrl(){
            debugger;
            let that=this;
            that.$http({
                method: 'post',
                url: fileOnlineUrl,
                baseURL:'/api',
                data: {
                    
                }
            }).then(function(response){
                if(response.data.code == 1) {
                    that.fileOnlinePerviewUrl =response.data.data;
                }else{
                    
                }
                
            }).catch(function(err){

            });
        },
    },
    mounted() {
        let that = this;
        that.getTreeData();
         that.getFileOnlineUrl();
    },
    updated() {
        let that = this;
        if (this.selectFlag) {
            //1页面加载完成左侧树默认选中
            // this.$refs.groupTreeData.setCurrentKey(that.defaultId);
            this.selectFlag = false;
        }
    },
};
</script>

<style scoped>
.mytree >>> .el-tree {
    height: 450px;
    overflow-y: auto;
    /* border-right: solid 1px #ddd; */
}
.mytree >>> .el-tree::-webkit-scrollbar {
    width: 10px;
}
div::-webkit-scrollbar{
  width:10px;
  height:10px;
  /**/
}
div::-webkit-scrollbar-track{
  background: rgb(239, 239, 239);
  border-radius:2px;
}
div::-webkit-scrollbar-thumb{
  background: #bfbfbf;
  border-radius:10px;
}
/* div::-webkit-scrollbar-thumb:hover{
  background: #333;
}
div::-webkit-scrollbar-corner{
  background: #179a16;
} */
.inputWidth {
    width: 77%;
}

.headerCoster {
    height: 59px;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
}

/*计数*/
.countNumber {
    margin-right: 23%;
}

.submitButton {
    margin-left: 19%;
}

/*.roleCardHight {*/
/*height: 611px;*/
/*}*/

.cardMinWidth {
    min-width: 275px;
}

.cardWidth {
    width: 100%;
}
/* 去掉table 最底部的线 */
div /deep/ .el-table--border::after,
div /deep/ .el-table--group::after,
div /deep/ .el-table::before {
    background-color: transparent;
}
.el-tree {
    font-size: 14px;
}
.el-progress {
    float: right;
    width: 66%;
    padding-top: 5px;
}
.mytable {
    height: 510px;
    overflow: auto;
}
</style>